package com.agileai.pm.module.proc.handler;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.StandardListHandler;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.pm.cxmodule.ProcWeeklyManage;
import com.agileai.pm.domain.Consts;
import com.agileai.pm.domain.Project;
import com.agileai.pm.mail.MailModel;
import com.agileai.pm.mail.MailSender;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;

public class ProcWeeklyManageListHandler
        extends StandardListHandler {
    public ProcWeeklyManageListHandler() {
        super();
        this.editHandlerClazz = ProcWeeklyManageEditHandler.class;
        this.serviceId = buildServiceId(ProcWeeklyManage.class);
    }
   
    @PageAction
    public ViewRenderer prepareDisplay(DataParam param){
		mergeParam(param);
		initParameters(param);
		User user = (User) this.getUser();
		String userId = user.getUserId();
		int seeWeeklyLimitNum = getService().getLimitNum(userId);
		param.put("limitNum", seeWeeklyLimitNum);
		Project project = (Project)this.getSessionAttribute(Consts.ProjectSessionKey);
		param.put("projectId", project.getProjectId());
		
		List<DataRow> weeklyList = getService().findRecords(param);
		int weeklyListSize = weeklyList.size();
		for(int i = 0; i < weeklyListSize; i++){
			
			DataRow weeklyInfo = weeklyList.get(i);
			String weeklyId = weeklyInfo.stringValue("PWI_ID");
			DataParam detailedTypeParam = new DataParam();
			detailedTypeParam.put("PWI_ID", weeklyId);
			
			detailedTypeParam.put("PWD_TYPE", "THIS_WEEKLY");
			List<DataRow> thisWeeklyList = getService().findDetailedRecords(detailedTypeParam);
			int thisWeeklyListSize = thisWeeklyList.size();
			weeklyInfo.put("thisWeeklyList", thisWeeklyList);
			weeklyInfo.put("thisWeeklyListSize", thisWeeklyListSize);
			this.setColor(thisWeeklyList);
			
			detailedTypeParam.put("PWD_TYPE", "NEXT_WEEKLY");
			List<DataRow> nextWeeklyList = getService().findDetailedRecords(detailedTypeParam);
			int nextWeeklyListSize = nextWeeklyList.size();
			weeklyInfo.put("nextWeeklyList", nextWeeklyList);
			weeklyInfo.put("nextWeeklyListSize", nextWeeklyListSize);
			this.setColor(nextWeeklyList);
			
			detailedTypeParam.put("PWD_TYPE", "FOLLOW_WEEKLY");
			List<DataRow> followWeeklyList = getService().findDetailedRecords(detailedTypeParam);
			int followWeeklyListSize = followWeeklyList.size();
			weeklyInfo.put("followWeeklyList", followWeeklyList);
			weeklyInfo.put("followWeeklyListSize", followWeeklyListSize);
			this.setColor(followWeeklyList);
		}
		
		String outboxInfo = this.getService().getOutboxInfo(user.getUserId());
		DataRow inboxInfo = this.getService().getInboxInfo(project.getProjectId());
		this.setAttribute("outboxInfo", outboxInfo);
		this.setAttribute("inboxInfo", inboxInfo.stringValue("PR_MAIL"));
		this.setAttribute("inboxInfoName", inboxInfo.stringValue("PR_NAME"));
		String emailInfo = this.getService().getEmailInfo(project.getProjectId());
		try {
			JSONObject emailJson = new JSONObject(emailInfo);
			this.setAttribute("emailServer", emailJson.get("emailServer"));
			this.setAttribute("emailPost",  emailJson.get("emailPost"));
			this.setAttribute("emailPassWord",  emailJson.get("emailPassWord"));
			this.setAttribute("emailTemplate",  emailJson.get("emailTemplate"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		
		this.setAttributes(param);
		
		this.setRsList(weeklyList);
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}
    
    @PageAction
    public ViewRenderer saveWeeklyWork(DataParam param) {
    	String responseText = "fail";
    	String weeklyId = param.stringValue("PWI_ID");
    	String emailTheme = param.stringValue("emailContent");
    	this.getService().updateEmailTheme(weeklyId,emailTheme);
    	
    	int index = 0;
    	while(param.containsKey("thisWeekItemId"+index)){
    		String weeklyDetailedId = param.stringValue("thisWeekItemId"+index);
    		String weeklyDetailedExplain = param.stringValue("thisWeekItemExplain"+index);
    		this.getService().updateDetailedExplain(weeklyDetailedId,weeklyDetailedExplain);
    		index++;
    	}
    	index = 0;
    	while(param.containsKey("nextWeekItemId"+index)){
    		String weeklyDetailedId = param.stringValue("nextWeekItemId"+index);
    		String weeklyDetailedExplain = param.stringValue("nextWeekItemExplain"+index);
    		this.getService().updateDetailedExplain(weeklyDetailedId,weeklyDetailedExplain);
    		index++;
    	}
    	index = 0;
    	while(param.containsKey("followWeekItemId"+index)){
    		String weeklyDetailedId = param.stringValue("followWeekItemId"+index);
    		String weeklyDetailedExplain = param.stringValue("followWeekItemExplain"+index);
    		this.getService().updateDetailedExplain(weeklyDetailedId,weeklyDetailedExplain);
    		index++;
    	}
    	
    	responseText = "success";
    	return new AjaxRenderer(responseText);
    }
    
    @PageAction
    public ViewRenderer createTrace(DataParam param) { 
    	String responseText = "fail";
    	Project project = (Project)this.getSessionAttribute(Consts.ProjectSessionKey);
    	String projectId = project.getProjectId(); 
    	
    	String weeklyId = param.stringValue("PWI_ID");
    	boolean inspectExplain = this.inspectExplain(weeklyId, "THIS_WEEKLY");
    	if(!inspectExplain){
    		return new AjaxRenderer("未完成状态的周报必须写说明");
    	}
    	
    	String trackId = this.getService().getTrackId(weeklyId);
    	if(StringUtil.isNotNullNotEmpty(trackId)){
    		getService().delTrackInfo(trackId);
    	}
    	
		//人天查询与剩余人天处理
    	float sumDayNum = getService().getSumDayNum(projectId);
    	float thisWeekDayNum = getService().getThisWeekDayNum(weeklyId);
    	float lastSurplusDayNum = getService().getSurplusDayNum(projectId);
    	if(lastSurplusDayNum == (float)1.11){
    		lastSurplusDayNum = sumDayNum;
    	}
    	float thisSurplusDayNum = lastSurplusDayNum - thisWeekDayNum;
    	
    	String trackKey = KeyGenerator.instance().genKey();
    	DataParam trackParam = new DataParam();
    	trackParam.put("PPT_ID", trackKey);
    	trackParam.put("PPA_ID", projectId);
    	trackParam.put("PWI_ID", weeklyId);
    	trackParam.put("PPT_ONE_DAY", thisWeekDayNum);
    	trackParam.put("PPT_SUM_DAY", lastSurplusDayNum);
    	trackParam.put("PPT_SURPLUS", thisSurplusDayNum);
    	trackParam.put("PPT_DATE", param.stringValue("PWI_START_TIME"));
    	trackParam.put("PPT_DESCRIBE","");
    	trackParam.put("PPT_STATE","TRACK_INITIALIZATION");
    	String proTrackName = param.stringValue("PWI_NAME")+param.stringValue("PWI_START_TIME")+"至"+param.stringValue("PWI_END_TIME")+"追踪";
    	trackParam.put("PPT_NAME",proTrackName);
    	this.getService().createTrackRecord(trackParam);
    	

    	//获取本周计划明细
    	DataParam detailedTypeParam = new DataParam();
		detailedTypeParam.put("PWI_ID", weeklyId);
		detailedTypeParam.put("PWD_TYPE", "THIS_WEEKLY");
		List<DataRow> thisWeeklyList = getService().findDetailedRecords(detailedTypeParam);
		List<DataParam> thisWeeklyParamList = new ArrayList<DataParam>();
		int listSize = thisWeeklyList.size();
		for(int i = 0; i < listSize; i++){
			DataRow row = thisWeeklyList.get(i);
			DataParam tempParam = row.toDataParam();
			String trackDetailedKey = KeyGenerator.instance().genKey();
			tempParam.put("PTD_ID", trackDetailedKey);
			tempParam.put("PPT_ID", trackKey);
			thisWeeklyParamList.add(tempParam);
		}
		this.getService().createTrackDetailedRecords(thisWeeklyParamList);
    	responseText = "success";
    	this.getService().updateWeeklyState(weeklyId, "TRACK_OVER");
    	return new AjaxRenderer(responseText);
    }
    
    @PageAction
    public ViewRenderer saveDisplayCount(DataParam param)  { 
    	int limitNum = Integer.parseInt(param.getString("limitNum"));
    	User user = (User) this.getUser();
    	String userId = user.getUserId();
    	this.getService().updateLimitNum(userId, limitNum);
    	
    	return this.prepareDisplay(param);
    }
    
    @PageAction
    public ViewRenderer sendEmail(DataParam param) throws Exception { 
    	String responseText = "fail";
    	String emailInbox = param.stringValue("emailInbox");
    	String emailOutbox = param.stringValue("emailOutbox");
    	String emailTitle = param.stringValue("emailTitle");
    	String emailServer = param.stringValue("emailServer");
    	String emailPost = param.stringValue("emailPost");
    	String emailPassWord = param.stringValue("emailPassWord");
    	String emailWeeklyId = param.stringValue("emailWeeklyId");
    	
    	String tabCss = "<style type='text/css'> .weekly-table{width:99%;border:1px solid #D9D9D9;border-collapse:collapse}.weekly-table td{border:1px solid #D9D9D9;} textarea{disabled:true}</style>";
	    MailModel mailModel = new MailModel();
	    
	    mailModel.setMailServerHost(emailServer);    
	    mailModel.setMailServerPort(emailPost);
	    mailModel.setValidate(true);
	    mailModel.setUserName(emailOutbox);
	    mailModel.setPassword(emailPassWord);
	    
	    mailModel.setFromAddress(emailOutbox);
	    mailModel.setToAddress(emailInbox);
	    mailModel.setSubject(emailTitle);
	    mailModel.setContent(tabCss+param.get("emailSubject"));
	     
	    MailSender sms = new MailSender();
	    sms.sendHtmlMail(mailModel);
    	
    	responseText = "success";
    	this.getService().updateWeeklyState(emailWeeklyId,"SEND_OVER");
    	return new AjaxRenderer(responseText);
    }
    
    @PageAction
    public ViewRenderer cahangWeekLyType(DataParam param) throws Exception { 
    	String responseText = "fail";
    	param.put("PWI_STATE", "");
    	this.getService().updateRecord(param);
    	
    	responseText = "success";
    	return new AjaxRenderer(responseText);
    }
    
    protected void setColor(List<DataRow> list) {
    	int listSize = list.size();
    	for(int i = 0; i < listSize; i++){
    		DataRow row = list.get(i);
    		String state = row.stringValue("PWD_STATE");
    		if("NOTSTART".equals(state)){
    			row.put("color", "");
    		}else if("ONGOING".equals(state)){
    			row.put("color", "color:blue;");
    		}else if("COMPLETED".equals(state)){
    			row.put("color", "color:green;");
    		}else{
    			row.put("color", "");
    		}
    	}
    	
    }
    
    protected boolean inspectExplain(String weeklyId ,String weeklyState) {
    	boolean result = true;
    	DataParam detailedTypeParam = new DataParam();
		detailedTypeParam.put("PWI_ID", weeklyId);
		detailedTypeParam.put("PWD_TYPE", weeklyState);
		List<DataRow> thisWeeklyList = getService().findDetailedRecords(detailedTypeParam);
    	int listSize = thisWeeklyList.size();
    	for(int i = 0; i < listSize; i++){
    		DataRow row = thisWeeklyList.get(i);
    		String detailedState = row.stringValue("PWD_STATE") ;
    		String detailedExplain = row.stringValue("PWD_EXPLAIN") ;
    		if((!"COMPLETED".equals(detailedState))&&StringUtil.isNullOrEmpty(detailedExplain)){
    			result = false;
    		}
    	}
    	return result;
    }

    protected void processPageAttributes(DataParam param) {
    }

    protected void initParameters(DataParam param) {
    	Date lastMonthDate = DateUtil.getDateAdd(new Date(), DateUtil.MONTH, -1);
    	lastMonthDate = DateUtil.getBeginOfMonth(lastMonthDate);
    	
    	initParamItem(param, "startTime", DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL, lastMonthDate));
        initParamItem(param, "endTime", DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL, new Date()));
    }

    protected ProcWeeklyManage getService() {
        return (ProcWeeklyManage) this.lookupService(this.getServiceId());
    }
}
